#!/usr/bin/perl -w

die unless @ARGV>1;

$pwd = $ENV{PWD};

$imglist = join(" ", @ARGV);

$rawpto = `tempfile --directory $pwd --prefix tmp --suffix .pto`;

chomp $rawpto;
`autopano-c-complete --output $rawpto $imglist`;

@fovptos = `pto-fov.pl $rawpto`;

foreach $fovpto (@fovptos) {

    $tempfile[0] = `tempfile --directory $pwd --prefix tmp --suffix .pto`;
    $tempfile[1] = `tempfile --directory $pwd --prefix tmp --suffix .pto`;
    $tempfile[2] = `tempfile --directory $pwd --prefix tmp --suffix .pto`;
    $tempfile[3] = `tempfile --directory $pwd --prefix tmp`;
    `rm $tempfile[3]`;
    $tempfile[4] = `tempfile --directory $pwd --prefix tmp --suffix .tif`;
    $tempfile[5] = `tempfile --directory $pwd --prefix tmp --suffix .jpg`;
    chomp @tempfile;

    `ptoclean -v --output $tempfile[0] $fovpto`;
    
    `autooptimiser -a -l -s -o $tempfile[1] $tempfile[0]`;
    `ptovariable --vignetting --response --exposure $tempfile[1]`;
    `vig_optimize -o $tempfile[2] $tempfile[1]`;
    `nona -m TIFF_m -o $tempfile[3] $tempfile[2]`;
    @tmptiffs = `ls $tempfile[3]\*`;
    chomp @tmptiffs;
    $tmptiffline = join(" ", @tmptiffs);
    `enblend -o $tempfile[4] $tmptiffline`;
    `convert $tempfile[4] -trim $tempfile[5]`;



    for($i=0; $i < @tempfile - 1; $i++) {
        `rm $tempfile[$i]*`;
    }

    print "$tempfile[@tempfile-1]\n";
}

$rawpto =~ /(.*)\.pto/;
`rm $1*`;

foreach(@ARGV) {
    `rm $_.key`;
}
